import tracker from '../utils/tracker'
// 接口异常捕获通过改写原型方法实现
// 缓存当前open函数 然后进行改写,接收参数保存到当前this上
// 为了避免接口死循环检测，应当过滤请求接口
// 然后apply调用旧的open
// send重写，函数科里化接收事件监听类型，并拼接参数send到监控接口
export function injectXHR(){
  let XMLHttpRequest = window.XMLHttpRequest
  let oldOpen = XMLHttpRequest.prototype.open
  XMLHttpRequest.prototype.open = function(method,url,async,username,password){
    // 防止重复死循环，不检测上报接口
      if (!url.match(/logstores/) && !url.match(/sockjs/)) {
          this.logData = {
              method, url, async, username, password
          }
      }
      return oldOpen.apply(this,arguments)
  }
  let oldSend = XMLHttpRequest.prototype.send
  let start;
  XMLHttpRequest.prototype.send = function(body){
    if(this.logData){
      start = Date.now()
      // 函数科里化
      let handler = (type)=>(event)=>{
        let duration = Date.now() - start
        let status = this.status
        let statusText = this.statusText
        tracker.send({ //未捕获的promise错误
          kind: 'stability',//稳定性指标
          type: 'xhr',//xhr
          eventType: type,//load error abort
          pathname: this.logData.url,//接口的url地址
          status: status + "-" + statusText,
          duration: "" + duration,//接口耗时
          response: this.response ? JSON.stringify(this.response) : "",
          params: body || ''
        })
      }
      this.addEventListener('load',handler('load'),false)
      this.addEventListener('error',handler('error'),false)
      this.addEventListener('abort',handler('abort'),false)
    }
    oldSend.apply(this,arguments)
  }
}